package impl

import (
	"context"
	"fmt"
	"time"

	"gitee.com/ChangPaoZhe/devops/apps/cmdb"
	"github.com/google/uuid"
	"go.mongodb.org/mongo-driver/bson"
)

func DefaultRandom()  string  {
	randomUUID, err := uuid.NewRandom()
	if err != nil {
		panic(err)
	}
	return   randomUUID.String()
}



func NewDefaultSearchReponseResource() *cmdb.SearchReponseResource{
	return &cmdb.SearchReponseResource{
		Values: make([]*cmdb.Resource, 0),
	}
}

func  NewDefaultSearchRequest() *cmdb.SearchRequest {
	return  &cmdb.SearchRequest{
	}
}


func  NewDefaultResource() *cmdb.Resource  {
	return  &cmdb.Resource{
		Port: 22,
		Create_At: time.Now().Unix(),
	}
}

func NewDefaultHealth(resource *cmdb.Resource) *cmdb.HealthSave {
	return  &cmdb.HealthSave{
		UploadAt: time.Now().Unix(),
		Resource: resource,
		Id: DefaultRandom(),
	}
}

func NewDefaultResourceStatus(resource *cmdb.Resource) *cmdb.ResourceStatus {
	return  &cmdb.ResourceStatus{
		Id: DefaultRandom(),
		Resource: resource,
		ResourceStatus:  cmdb.Resource_Status_OnLine,
	}
}
// 将 MongoDB 中的 ObjectID 类型转换为 Protocol Buffers 中的 bytes 类型
func (c *CmdbImpl) Search(ctx  context.Context,req  *cmdb.SearchRequest) (*cmdb.SearchReponseResource, error) {
		var  searchResponse []*cmdb.Resource
		filter:=bson.M{}
		if  req.Region=="" && req.Ipaddress=="" && req.SystemName=="" && req.Id == "" {
			msg:="param  is null"
			c.logger.Error().Msg(msg)
			return  nil,fmt.Errorf(msg)
		}
		collection:=c.MongoDb.Collection("register")
		if req.Id !=""{
			filter=bson.M{"_id": req.Id}
		}else  {
			if  req.Region==""{
				if req.SystemName==""{
					filter=bson.M{"ipaddress": req.Ipaddress}
				}else if  req.Ipaddress==""{
					filter=bson.M{"system_name": req.SystemName}
				}else {
					filter=bson.M{"$and": []bson.M{bson.M{"ipaddress": req.Ipaddress},bson.M{"system_name": req.SystemName}}}
				}
			}else if  req.Ipaddress=="" {
				if req.SystemName==""{
					filter=bson.M{"region": req.Region}
				} else {
					filter=bson.M{"$and":[]bson.M{bson.M{"region":req.Region},bson.M{"system_name": req.SystemName}}}
				}
			} else if  req.SystemName=="" {
				filter=bson.M{"$and":[]bson.M{bson.M{"region":req.Region},bson.M{"ipaddress": req.Ipaddress}}}
			}else  {
				filter=bson.M{"$and":[]bson.M{bson.M{"region":req.Region},bson.M{"ipaddress": req.Ipaddress},bson.M{"system_name": req.SystemName}}}
			}
		}
		msg:=fmt.Sprintf("filter: %#v",filter)
		c.logger.Info().Msg(msg)
		cousor,err:=collection.Find(ctx, filter)
		if err != nil {
			c.logger.Error().Msg(err.Error())
			return nil,err
		}
		err = cousor.All(context.TODO(), &searchResponse)
		
		if err != nil {
			c.logger.Error().Msg(err.Error())			
			return  nil,err
		}
		resource:=NewDefaultSearchReponseResource()
		resource.Totalcount=int64(len(searchResponse))
		searchcmdbRespone:=make([]*cmdb.Resource,0,resource.Totalcount)
		if resource.Totalcount == 0 {
			msg:=fmt.Sprintf("未查询到设备")
			c.logger.Error().Msg(msg)
			return nil,fmt.Errorf("未查询到设备") 
		}
		for  _,value:= range searchResponse {
			resorces:=&cmdb.Resource{}
			resorces=value
			searchcmdbRespone = append(searchcmdbRespone, resorces)
		}
		resource.Values=searchcmdbRespone
		return resource,nil 
}
func (c *CmdbImpl) Register(ctx  context.Context,req  *cmdb.RegisterRequest) (*cmdb.Resource, error){
	if req.Key!="Mysql#12345" {
		msg:="key error,register failed"
		c.logger.Error().Msg(msg)
		return  nil,fmt.Errorf(msg)
	}
	searchrequest:=NewDefaultSearchRequest()
	if req.Resource.Id!=""{
		searchrequest.Id=req.Resource.Id
	}
	searchrequest.Ipaddress=req.Resource.Ipaddress
	searchrequest.SystemName=req.Resource.SystemName
	searchrequest.Region=req.Resource.Region
	resources,err:=c.Search(ctx,searchrequest)
	if err == nil   && resources.Totalcount !=0  {
		msg:=fmt.Errorf("资源已注册，请勿重新注册！！！%s",resources.String())
		c.logger.Error().Msg(msg.Error())
		return nil, msg
	}
	collection:=c.MongoDb.Collection("register")
	res:=NewDefaultResource()
	req.Resource.Id=DefaultRandom()
	res=req.Resource
	_,err=collection.InsertOne(ctx, res)  //插入数据
	if  err != nil{
		c.logger.Error().Msg(err.Error())
		return nil,err 
	}
	res.Password=""
	c.logger.Info().Msg(fmt.Sprintf("主机:%s注册成功,IP地址:%s", res.Hostname,res.Ipaddress))
	return res,nil
}

// 定期上报数据
func (c *CmdbImpl)    Healther(ctx  context.Context,req  *cmdb.RequestHealth) (*cmdb.HealthSave, error) {
	collection:=c.MongoDb.Collection("health")
	searchrequest:=NewDefaultSearchRequest()
	searchrequest.Ipaddress=req.IpAddress
	searchrequest.Region=req.Region
	resouces,err:=c.Search(ctx,searchrequest)
	if err != nil {
		return nil, err
	}
	for  _,resource:=range resouces.Values {
		health:=NewDefaultHealth(resource)
		_,err:=collection.InsertOne(ctx, health)
		if err != nil {
			return nil, err
		}
		return  health,nil 
	}
	return nil,nil 
}

